const Product = require('../models/Product');
const catchAsync = require('../middleware/catchAsync');

// 获取所有商品
exports.getAllProducts = catchAsync(async (req, res, next) => {
    try {
        const products = await Product.findAll();
        res.json({ data: products });
    } catch (error) {
        next(error);
    }
});

// 获取单个商品
exports.getProduct = catchAsync(async (req, res, next) => {
    try {
        const productId = parseInt(req.params.id);
        
        if (isNaN(productId) || productId <= 0) {
            return res.status(400).json({ message: '无效的商品ID' });
        }

        const product = await Product.findById(productId);
        
        if (!product) {
            return res.status(404).json({ message: '商品不存在' });
        }

        res.json({ data: product });
    } catch (error) {
        next(error);
    }
});

// 创建商品
exports.createProduct = catchAsync(async (req, res, next) => {
    try {
        const { name, code, category_id, price, cost, unit, stock, min_stock, status = 'active' } = req.body;

        // 验证必填字段
        if (!name || !code || !category_id || !price || !unit) {
            return res.status(400).json({ message: '名称、编码、分类、价格和单位为必填项' });
        }

        // 检查编码是否已存在
        const codeExists = await Product.checkCodeExists(code);
        if (codeExists) {
            return res.status(400).json({ message: '商品编码已存在' });
        }

        const productId = await Product.create({
            name,
            code,
            category_id,
            price,
            cost: cost || 0,
            unit,
            stock: stock || 0,
            min_stock: min_stock || 0,
            status: status || 'active'
        });

        res.status(201).json({
            message: '商品创建成功',
            data: { id: productId, ...req.body }
        });
    } catch (error) {
        next(error);
    }
});

// 更新商品
exports.updateProduct = catchAsync(async (req, res, next) => {
    try {
        const productId = parseInt(req.params.id);
        const { name, code, category_id, price, cost, unit, stock, min_stock, status } = req.body;

        if (isNaN(productId) || productId <= 0) {
            return res.status(400).json({ message: '无效的商品ID' });
        }

        // 验证必填字段
        if (!name || !code || !category_id || !price || !unit) {
            return res.status(400).json({ message: '名称、编码、分类、价格和单位为必填项' });
        }

        // 检查编码是否被其他商品使用
        const codeExists = await Product.checkCodeExists(code, productId);
        if (codeExists) {
            return res.status(400).json({ message: '商品编码已存在' });
        }

        const success = await Product.update(productId, {
            name,
            code,
            category_id,
            price,
            cost: cost || 0,
            unit,
            stock: stock || 0,
            min_stock: min_stock || 0,
            status: status || 'active'
        });

        if (!success) {
            return res.status(404).json({ message: '商品不存在' });
        }

        res.json({
            message: '商品更新成功',
            data: { id: productId, ...req.body }
        });
    } catch (error) {
        next(error);
    }
});

// 更新商品库存
exports.updateStock = catchAsync(async (req, res, next) => {
    try {
        const productId = parseInt(req.params.id);
        const { quantity, type } = req.body;

        if (isNaN(productId) || productId <= 0) {
            return res.status(400).json({ message: '无效的商品ID' });
        }

        if (!quantity || typeof quantity !== 'number' || quantity <= 0) {
            return res.status(400).json({ message: '数量必须是大于0的数字' });
        }

        if (!type || !['in', 'out'].includes(type)) {
            return res.status(400).json({ message: '类型必须是 in 或 out' });
        }

        const product = await Product.findById(productId);
        if (!product) {
            return res.status(404).json({ message: '商品不存在' });
        }

        let newStock = product.stock;
        if (type === 'in') {
            newStock += quantity;
        } else {
            if (product.stock < quantity) {
                return res.status(400).json({ message: '库存不足' });
            }
            newStock -= quantity;
        }

        const success = await Product.update(productId, {
            ...product,
            stock: newStock
        });

        if (!success) {
            return res.status(404).json({ message: '商品不存在' });
        }

        res.json({
            message: '库存更新成功',
            data: { id: productId, stock: newStock }
        });
    } catch (error) {
        next(error);
    }
});

// 更新商品状态
exports.updateStatus = catchAsync(async (req, res, next) => {
    try {
        const productId = parseInt(req.params.id);
        const { status } = req.body;

        if (isNaN(productId) || productId <= 0) {
            return res.status(400).json({ message: '无效的商品ID' });
        }

        if (!status || !['active', 'inactive'].includes(status)) {
            return res.status(400).json({ message: '状态必须是 active 或 inactive' });
        }

        const product = await Product.findById(productId);
        if (!product) {
            return res.status(404).json({ message: '商品不存在' });
        }

        const success = await Product.update(productId, {
            ...product,
            status
        });

        if (!success) {
            return res.status(404).json({ message: '商品不存在' });
        }

        res.json({
            message: '状态更新成功',
            data: { id: productId, status }
        });
    } catch (error) {
        next(error);
    }
});

// 删除商品
exports.deleteProduct = catchAsync(async (req, res, next) => {
    try {
        const productId = parseInt(req.params.id);

        if (isNaN(productId) || productId <= 0) {
            return res.status(400).json({ message: '无效的商品ID' });
        }

        const success = await Product.delete(productId);

        if (!success) {
            return res.status(404).json({ message: '商品不存在' });
        }

        res.json({ message: '商品删除成功' });
    } catch (error) {
        next(error);
    }
}); 